<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="700px" destroyOnClose showFooter>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./articleGroup.data"
  import { saveOrUpdateGroup } from "/@/api/sys/article"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"

  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
      })
    }
  })
  const title = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))
  async function handleSubmit(v) {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      values.userIds += ","
      await saveOrUpdateGroup(values, isUpdate.value)
      closeDrawer()
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
